package com.ld.shieldsb.db.model;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

import lombok.Data;

@Data
public class DBSetInfo {
    protected String dbSetName; // 连接名自定义
    protected String dbUserName;
    protected String dbPassword;
    protected String dbUrl;
    protected String host;
    protected String port; // 端口
    protected String dbName; // mysql等用

    public String getDbName() {
        if (dbName == null) {
//            dbName = StringUtils.substringAfterLast(getDbUrl(), "/");
//            if (dbName != null && dbName.contains("?")) {
//                dbName = StringUtils.substringBefore(dbName, "?");
//            }
            dbName = getDbUrl();
            if (dbName.contains("?")) { // 带参数
                dbName = StringUtils.substringBefore(dbName, "?");
            }
            dbName = StringUtils.substringAfterLast(dbName, "/");
        }
        return dbName;
    }

    public String getPort() {
        if (port == null) {
            port = StringUtils.substringAfterLast(getDbUrl(), ":");
            if (port != null && port.contains("/")) {
                port = StringUtils.substringBefore(port, "/");
            }
        }
        return port;
    }

    public static void main(String[] args) {
        String port = null;
        // 通过控制板输入想要输入的地址，然后测试是否符合规则
        String url = "jdbc:mysql://localhost:3306/bms?useUnicode=true&amp;amp;characterEncoding=UTF-8&amp;amp;useSSL=false";
        if (port == null) {
            port = StringUtils.substringAfterLast(url, ":");
            System.err.println(port);
            if (port != null && port.contains("/")) {
                port = StringUtils.substringBefore(port, "/");
            }
        }
        System.err.println(port);
    }

    /**
     * 
     * 根据dburl获取host
     * 
     * @Title getHost
     * @author 刘金浩
     * @date 2019年11月14日 上午9:47:32
     * @return String
     */
    public String getHost() {
        if (host == null) {
            String regEx = "((?<=//|)((\\w)+\\.)+\\w+)|(localhost)";
            Pattern p = Pattern.compile(regEx);
            Matcher m = p.matcher(dbUrl);
            while (m.find()) {
                String result = m.group();
                host = result;
            }
        }
        return host;
    }

}
